﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using UploadServer.middlewares;

namespace UploadServer
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        private IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<UploadServerConfig>(Configuration.GetSection("uploadServer"));
            services.AddSingleton<UploadMiddleware>();
            services.AddSingleton<ChunkUploadMiddleware>();
            services.AddSingleton<ThumbnailMiddleware>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<UploadServerConfig> config)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var provider = new FileExtensionContentTypeProvider();
            if (!string.IsNullOrEmpty(config.Value.AppendMimes))
            {
                foreach (var mimeItem in config.Value.AppendMimes.Split(';', StringSplitOptions.RemoveEmptyEntries))
                {
                    var parts = mimeItem.Split(':', StringSplitOptions.RemoveEmptyEntries);
                    provider.Mappings[parts[0]] = parts[1];
                }
            }

            //缩略图中间件
            app.UseWhen(
                context => context.Request.Path.StartsWithSegments(config.Value.VirtualPath,
                    StringComparison.OrdinalIgnoreCase),
                appBuilder => { appBuilder.UseMiddleware<ThumbnailMiddleware>(); });


            //静态文件访问
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(config.Value.PhysicalPath),
                RequestPath = config.Value.VirtualPath,
                ContentTypeProvider = provider,
                OnPrepareResponse = (ctx) =>
                {
                    ctx.Context.Response.Headers.Append("Cache-Control",
                        $"public, max-age={config.Value.ResponseCache}");
                }
            });

            //传统上传
            app.UseWhen(
                context => context.Request.Path.StartsWithSegments(config.Value.EntryPoint1,
                    StringComparison.OrdinalIgnoreCase),
                appBuilder => { appBuilder.UseMiddleware<UploadMiddleware>(); });

            //分片上传
            app.UseWhen(
                context => context.Request.Path.StartsWithSegments(config.Value.EntryPoint2,
                    StringComparison.OrdinalIgnoreCase),
                appBuilder => { appBuilder.UseMiddleware<ChunkUploadMiddleware>(); });


            //访问根目录
            app.UseWhen(context => context.Request.Path.Value.Equals("/"),
                builder => builder.Run(async ctx => { await ctx.Response.WriteAsync("Hello UploadServer !"); }));

            app.Run(async context =>
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsync("not found:" + context.Request.Path.Value);
            });
        }
    }
}